package cn.com.generaldata.os.ws.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.annotation.InjectName;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.com.generaldata.os.constant.FilterConstant;
import cn.com.generaldata.os.newpojo.ReportType;
import cn.com.generaldata.os.paging.Filter;
import cn.com.generaldata.os.paging.FilterRule;
import cn.com.generaldata.os.paging.Page;
import cn.com.generaldata.os.pojo.DustryReport;
import cn.com.generaldata.os.pojo.Industry;
import cn.com.generaldata.os.pojo.UserIndustry;
import cn.com.generaldata.os.service.common.IndustryService;
import cn.com.generaldata.os.service.common.UserService;
import cn.com.generaldata.os.vo.IndustryVO;
import cn.com.generaldata.os.vo.ResultVO;

@InjectName
@Component
public class IndustryWS {

	@Autowired
	private IndustryService industryService;
	@Autowired
	private UserService userService;
	
	@Autowired
	private ReportWS reportService;

	@At("/industryManage/create")
	@Ok("jsp:/static/admin/unit/uploadOk")
	public void createIndustry(@Param("..") IndustryVO industry, HttpServletRequest request) {
		industryService.createIndustry(toPojo(industry), toPojoReportTypes(industry));
		request.setAttribute("msg", "增加成功。");
	}

	@At("/industryManage/add")
	@Ok("jsp:/static/admin/industryManage/add")
	public void addIndustry() {

	}

	@At("/industryManage/modify")
	@Ok("jsp:/static/ocean/unit/ok")
	public IndustryVO modifyIndustry(@Param("..") IndustryVO industry, String[] noReportTypes) {
		return toVo(industryService.modifyIndustry(toPojo(industry), toPojoReportTypes(industry), noReportTypes));
	}

	@At("/industryManage/edit")
	@Ok("jsp:/static/admin/industryManage/edit")
	public void editIndustry(@Param("id") String id, HttpServletRequest request) {
		IndustryVO industry = queryIndustryById(id);
		request.setAttribute("industry", industry);
	}

	public IndustryVO queryIndustryById(String id) {
		return toVo(industryService.queryIndustryById(id));
	}

	public ResultVO<IndustryVO> queryIndustryList() {
		return toVoResult(industryService.queryIndustries(null, null));
	}

	public ResultVO<IndustryVO> queryIndustries(String industryName, String typeId, Integer pageNum) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		// filter.setSortBy("xl");
		// filter.setSortBy("zl");
		filter.setSortBy("dl");
		if (StringUtils.isNotBlank(industryName)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "dustryName", "%" + industryName.trim() + "%"));
		}

		if (StringUtils.isNotBlank(typeId)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "typeId", typeId));
		}

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(industryService.queryIndustries(filter, page));
	}

	@At("/industryManage/list")
	@Ok("jsp:/static/admin/industryManage/list")
	public ResultVO<IndustryVO> queryIndustry(@Param("industryName") String industryName, @Param("code") String code,
			@Param("p") Integer pageNum) {

		String hql = "from Industry where 1=1";
		HashMap map = new HashMap();
		if (StringUtils.isNotBlank(industryName)) {
			hql += " and dustryName like :industryName";
			map.put("industryName", "%" + industryName.trim() + "%");

		}

		if (StringUtils.isNotBlank(code)) {
			hql += " and dl like :code";
			map.put("code", "%" + code.trim() + "%");
		}
		hql += " order by dl,zl,xl";
		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}else{
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(industryService.queryIndustriesByhql(hql, map, page));
	}

	@At("/reportgroup/reportgroup")
	@Ok("jsp:/static/admin/reportgroup/reportgroup")
	public ResultVO<IndustryVO> queryDLIndustries(@Param("industryName") String industryName,
			@Param("typeId") String typeId, @Param("p") Integer pageNum) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		// filter.setSortBy("xl");
		// filter.setSortBy("zl");
		filter.setSortBy("dl");
		if (StringUtils.isNotBlank(industryName)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "dustryName", "%" + industryName.trim() + "%"));
		}

		if (StringUtils.isNotBlank(typeId)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "typeId", typeId));
		}

		filter.addRule(new FilterRule(FilterConstant.NOT_NULL, "dl", null));

		// filter.addRule(new FilterRule(FilterConstant.GET_NULL, "zl", null));
		filter.addRule(new FilterRule(FilterConstant.OR, "zl", ""));

		// filter.addRule(new FilterRule(FilterConstant.GET_NULL, "xl", null));
		filter.addRule(new FilterRule(FilterConstant.OR, "xl", ""));

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		}else{
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(industryService.queryIndustries(filter, page));
	}
	
	/**
	 * 报表分组信息修改
	 * */
	@At("/reportgroup/edit/?")
	@Ok("jsp:/static/admin/reportgroup/reportgroupedit")
	public Industry reportGroupEdit(String id, HttpServletRequest request) {
		
		request.setAttribute("reportTypeList", reportService.queryType());
		
		return industryService.queryIndustryById(id);
	}
	
	/**
	 * 报表分组信息修改
	 * */
	@At("/reportgroup/modify")
	@Ok("json")
	public String reportGroupEdit(@Param("..") IndustryVO industry, @Param("reportTypes") String reportTypes, @Param("noReportTypes") String noReportTypes) {
		
		List<String> reportTypeIds = Arrays.asList(reportTypes.split(","));
		industry.setReportTypeIds(reportTypeIds);
		
		String[] delnoReportTypes = null;
		if (noReportTypes!=null){
			delnoReportTypes = noReportTypes.split(",");
		}
		
		if (modifyIndustry(industry, delnoReportTypes)!=null){
			return "success";
		}
		return "";
	}
	

	@At("/user/industrySelect")
	@Ok("jsp:/static/admin/user/information/industrySelect")
	public ResultVO<IndustryVO> queryDLIndustries1(@Param("industryName") String industryName,
			@Param("typeId") String typeId, @Param("p") Integer pageNum) {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		// filter.setSortBy("xl");
		// filter.setSortBy("zl");
		filter.setSortBy("dl");
		if (StringUtils.isNotBlank(industryName)) {
			filter.addRule(new FilterRule(FilterConstant.LIKE, "dustryName", "%" + industryName.trim() + "%"));
		}

		if (StringUtils.isNotBlank(typeId)) {
			filter.addRule(new FilterRule(FilterConstant.EQUAL, "typeId", typeId));
		}

		filter.addRule(new FilterRule(FilterConstant.NOT_NULL, "dl", null));

		// filter.addRule(new FilterRule(FilterConstant.GET_NULL, "zl", null));
		filter.addRule(new FilterRule(FilterConstant.OR, "zl", ""));

		// filter.addRule(new FilterRule(FilterConstant.GET_NULL, "xl", null));
		filter.addRule(new FilterRule(FilterConstant.OR, "xl", ""));

		Page page = null;
		if (pageNum != null) {
			page = new Page(pageNum, ResultVO.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page(1, ResultVO.DEFAULT_PAGE_SIZE);
		}
		return toVoResult(industryService.queryIndustries(filter, page));
	}

	@At("/industryManage/allList")
	@Ok("json")
	public ResultVO<IndustryVO> queryAllDLIndustries() {
		Filter filter = new Filter();
		filter.setOrder(FilterConstant.ASC);
		// filter.setSortBy("xl");
		// filter.setSortBy("zl");
		filter.setSortBy("dl");
		filter.addRule(new FilterRule(FilterConstant.NOT_NULL, "dl", null));

		// filter.addRule(new FilterRule(FilterConstant.GET_NULL, "zl", null));
		filter.addRule(new FilterRule(FilterConstant.OR, "zl", ""));

		// filter.addRule(new FilterRule(FilterConstant.GET_NULL, "xl", null));
		filter.addRule(new FilterRule(FilterConstant.OR, "xl", ""));

		Page page = null;
		return toVoResult(industryService.queryIndustries(filter, page));
	}

	public List<IndustryVO> queryAllIndustries() {
		return queryIndustries(null, null, null).getOperationResult();
	}

	public List<IndustryVO> queryIndustriesByName(String name) {
		return queryIndustries(name, null, null).getOperationResult();
	}

	public List<IndustryVO> queryIndustriesByTypeId(String typeId) {
		return queryIndustries(null, typeId, null).getOperationResult();
	}

	public List<IndustryVO> queryIndustriesByUserId(String userId) {
		if (userId != null) {
			HashMap map = new HashMap();
			String hql = "from Industry as it where exists(select ui.id from UserIndustry as ui where ui.industry.id=it.id and ui.user.id=:userId) order by dl asc";
			map.put("userId", userId);
			// String[] split = ids.split(",");
			// filter.addRule(new FilterRule(FilterConstant.COLLECTION, "id", split));
			// filter.setOrder(FilterConstant.ASC);
			// filter.setSortBy("report.reportTypeCode");

			cn.com.generaldata.os.paging.Result result = industryService.queryIndustriesByhql(hql, map, null);
			return toVoList(result);
			// }
			// }
		}
		return null;
	}

	@At("/industryManage/deleteMany")
	@Ok("json")
	public String removeIndustries(@Param("idStr") String idStr) {

		String[] idArray = idStr.split(",");
		industryService.removeIndustries(idArray);
		return "{id:0}";

	}

	public void setIndustryService(IndustryService industryService) {
		this.industryService = industryService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	private cn.com.generaldata.os.pojo.Industry toPojo(IndustryVO industry) {
		if (industry != null) {
			cn.com.generaldata.os.pojo.Industry pIndustry = new cn.com.generaldata.os.pojo.Industry(industry.getId(),
					industry.getDustryName(), industry.getDustryDesc(), industry.getTypeId(), industry.getDl(),
					industry.getZl(), industry.getXl(), industry.getCode(), null, null);

			return pIndustry;
		}
		return null;
	}

	private List<ReportType> toPojoReportTypes(IndustryVO industry) {
		if (industry != null) {
			if (industry.getReportTypeIds() != null) {
				List<ReportType> reportTypes = new ArrayList<ReportType>();
				for (String reportTypeId : industry.getReportTypeIds()) {
					if (reportTypeId != null) {
						ReportType reportType = new ReportType();
						reportType.setId(reportTypeId);
						reportTypes.add(reportType);
					}
				}
				return reportTypes;
			}
		}
		return null;
	}

	private IndustryVO toVo(cn.com.generaldata.os.pojo.Industry pIndustry) {
		if (pIndustry != null) {
			List<String> reportTypeIds = new ArrayList<String>();
			if (pIndustry.getDustryReports() != null) {
				for (DustryReport dustryReport : pIndustry.getDustryReports()) {
					reportTypeIds.add(dustryReport.getReportTypeId());
				}
			}

			List<String> userIds = new ArrayList<String>();
			if (pIndustry.getUserIndustrys() != null) {
				for (UserIndustry userIndustry : pIndustry.getUserIndustrys()) {
					userIds.add(userIndustry.getUser().getId());
				}
			}

			return new IndustryVO(pIndustry.getId(), pIndustry.getDustryName(), pIndustry.getDustryDesc(),
					pIndustry.getTypeId(), pIndustry.getDl(), pIndustry.getZl(), pIndustry.getXl(),
					pIndustry.getCode(), reportTypeIds, userIds);
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	private List<IndustryVO> toVoList(cn.com.generaldata.os.paging.Result pResult) {
		List<IndustryVO> industries = new ArrayList<IndustryVO>();
		for (cn.com.generaldata.os.pojo.Industry pIndustry : (List<cn.com.generaldata.os.pojo.Industry>) pResult
				.getOperationResult()) {
			industries.add(toVo(pIndustry));
		}
		return industries;
	}

	@SuppressWarnings("unchecked")
	private ResultVO<IndustryVO> toVoResult(cn.com.generaldata.os.paging.Result pResult) {
		ResultVO<IndustryVO> result = new ResultVO<IndustryVO>();

		List<IndustryVO> industries = new ArrayList<IndustryVO>();
		for (cn.com.generaldata.os.pojo.Industry pIndustry : (List<cn.com.generaldata.os.pojo.Industry>) pResult
				.getOperationResult()) {
			industries.add(toVo(pIndustry));
		}
		result.setOperationResult(industries);
		result.setPageNumber(pResult.getPageNumber());
		result.setPageSize(pResult.getPageSize());
		result.setTotalCount(pResult.getTotalCount());

		return result;
	}

}
